﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

namespace HideRibbonItems.Layouts.HideRibbonItems
{
    public partial class ribbonItems : LayoutsPageBase
    {
        const string ribbonMenuItems = "ribbonMenuItems";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                addImageButton.ImageUrl = SPContext.Current.Site.Url + "/_layouts/images/HideRibbonItems/add.png";
                saveImg.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/HideRibbonItems/save.png";
                cancelImg.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/HideRibbonItems/cancel.png";

                bindDocumentLibraries();
                bindRibbonItems();
                bindGroups();
                bindRepeater();
            }
        }
        protected void documentRibbonRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                RibbonLibraryItem rli = (RibbonLibraryItem)e.Item.DataItem;

                Literal documentsLiteral = (Literal)e.Item.FindControl("documentsLiteral");
                Literal ribbonItemsLiteral = (Literal)e.Item.FindControl("ribbonItemsLiteral");
                Literal groupsLiteral = (Literal)e.Item.FindControl("groupsLiteral");
                ImageButton editImg = (ImageButton)e.Item.FindControl("editImg");
                ImageButton deleteImg = (ImageButton)e.Item.FindControl("deleteImg");


                HtmlTable documentribbonTable = (HtmlTable)e.Item.FindControl("documentribbonTable");
                
                documentsLiteral.Text = rli.DocumentsText;
                ribbonItemsLiteral.Text = rli.RibbonItemsText;
                groupsLiteral.Text = rli.GroupsText;

                editImg.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/HideRibbonItems/edit.png";

                deleteImg.ImageUrl = SPContext.Current.Site.Url + "/_layouts/Images/HideRibbonItems/delete.png";

                deleteImg.CommandArgument = e.Item.ItemIndex.ToString();
                editImg.CommandArgument = e.Item.ItemIndex.ToString();

                bool setBG = true;
                if (ViewState["editIndex"] != null)
                {
                    int index = int.Parse(ViewState["editIndex"].ToString());

                    if (e.Item.ItemIndex == index)
                    {
                        documentribbonTable.BgColor = "#08246B";
                        documentribbonTable.Style.Add("color", "white");
                        setBG = false;
                    }
                }
                if (e.Item.ItemIndex % 2 == 1 && setBG)
                {
                    documentribbonTable.BgColor = "#e0e0e0";
                }
            }
        }

        #region Button handles
        protected void addImageButton_Click(object sender, EventArgs e)
        {
            RibbonLibraryItem rli = new RibbonLibraryItem();

            rli.Documents = getSelectedItems(librariesListBox);
            rli.RibbonItems = getSelectedItems(ribbonItemsListBox);
            rli.Groups = getSelectedItems(groupListBox);
            setWebPropertyRibbonMenu(rli);

            bindRepeater();
        }        
        protected void deleteImg_Click(object sender, EventArgs e)
        {
            deleteRibbonItem(int.Parse(((ImageButton)sender).CommandArgument));
        }
        protected void saveImg_Click(object sender, EventArgs e)
        {
            int index = int.Parse(ViewState["editIndex"].ToString());
            List<RibbonLibraryItem> rliList = getWebPropertyRibbonMenu();

            RibbonLibraryItem rli = rliList[index];

            rli.Documents = getSelectedItems(librariesListBox);
            rli.RibbonItems = getSelectedItems(ribbonItemsListBox);
            rli.Groups = getSelectedItems(groupListBox);

            updateRibbonMenu(rliList);
            // Visa Cancel och update
            cancelImg.Visible = false;
            saveImg.Visible = false;
            addImageButton.Visible = true;

            librariesListBox.ClearSelection();
            ribbonItemsListBox.ClearSelection();
            groupListBox.ClearSelection();
            ViewState["editIndex"] = null;

            bindRepeater();
        }
        protected void editImg_Click(object sender, EventArgs e)
        {
            int index = int.Parse(((ImageButton)sender).CommandArgument);
            ViewState["editIndex"] = index.ToString();
            editRibbonItem(index);


        }
        protected void cancelImg_Click(object sender, EventArgs e)
        {
            foreach (ListItem item in librariesListBox.Items)
            {
                item.Selected = false;
            }
            foreach (ListItem item in ribbonItemsListBox.Items)
            {
                item.Selected = false;
            }
            foreach (ListItem item in groupListBox.Items)
            {
                item.Selected = false;
            }

            // Visa Cancel och update
            cancelImg.Visible = false;
            saveImg.Visible = false;
            addImageButton.Visible = true;
            ViewState["editIndex"] = null;
        }
        #endregion

        #region Public
        public List<RibbonLibraryItem> getWebPropertyRibbonMenu()
        {
            List<RibbonLibraryItem> rliList = new List<RibbonLibraryItem>();
            string propertyText = SPContext.Current.Web.Properties[ribbonMenuItems];

            if (propertyText != null && propertyText != "")
            {
                // Härlig stränghantering! Lycka till och följa koden! /OG
                string[] splitRLI = propertyText.Split(';');
                foreach (string rliStrings in splitRLI)
                {
                    string[] rliString = rliStrings.Split('|');
                    RibbonLibraryItem rli = new RibbonLibraryItem();
                    // Documents
                    if (rliString.Length > 0)
                        rli.Documents = stringArrayToArrayList(rliString[0].Split(','));
                    // Ribbon
                    if (rliString.Length > 1)
                    {
                        rli.RibbonItems = stringArrayToArrayList(rliString[1].Split(','));
                    }
                    // Groups
                    if (rliString.Length > 2)
                    {
                        rli.Groups = stringArrayToArrayList(rliString[2].Split(','));
                    }
                    rliList.Add(rli);
                }
            }

            return rliList;
        }
        public SPList GetListByUrl(string listUrl)
        {
            SPList list = null;            

            try
            {
                using (SPSite site = new SPSite(listUrl))
                {
                    if (site != null)
                    {
                        // Strip off the site url, leaving the rest
                        // We'll use this to open the web
                        string webUrl = listUrl.Substring(site.Url.Length);

                        // Strip off anything after /forms/
                        int formsPos = webUrl.IndexOf("/forms/", 0, StringComparison.InvariantCultureIgnoreCase);
                        if (formsPos >= 0)
                        {
                            webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', formsPos));
                        }

                        // Strip off anything after /lists/
                        int listPos = webUrl.IndexOf("/lists/", 0, StringComparison.InvariantCultureIgnoreCase);
                        if (listPos >= 0)
                        {
                            // Must be a custom list
                            // Strip off anything after /lists/
                            webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', listPos));
                        }
                        else
                        {
                            // No lists, must be a document library.
                            // Strip off the document library name
                            webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/'));
                        }

                        // Get the web site
                        using (SPWeb web = site.OpenWeb(webUrl))
                        {
                            if (web != null)
                            {
                                // Initialize the web (avoids COM exceptions)
                                string title = web.Title;

                                // Strip off the relative list Url
                                // Form the full path to the list
                                //string relativeListUrl = listUrl.Substring(web.Url.Length);
                                //string url = SPUrlUtility.CombineUrl(web.Url, relativeListUrl);

                                // Get the list
                                list = web.GetList(listUrl);
                            }
                        }
                    }
                }
            }
            catch { }

            return list;
        }

        #endregion

        #region Private
        private void setWebPropertyRibbonMenu(RibbonLibraryItem rli)
        {
            string newRibbonMenu = string.Format(rli.DocumentsTextString + "|" + rli.RibbonItemsTextString + "|" + rli.GroupsTextString);
            string ribbonMenus = SPContext.Current.Web.Properties[ribbonMenuItems] != null ? SPContext.Current.Web.Properties[ribbonMenuItems] : "";
            string ribbonValue = string.Empty;
            if (ribbonMenus.Length > 0)
                ribbonValue = ribbonMenus + ";" + newRibbonMenu;
            else
                ribbonValue = newRibbonMenu;
            // Sätt webb property!
            SPWeb web = SPContext.Current.Web;
            web.AllowUnsafeUpdates = true;
            if (web.Properties[ribbonMenuItems] == null)
                web.Properties.Add(ribbonMenuItems, ribbonValue);
            else
                web.Properties[ribbonMenuItems] = ribbonValue;
            web.Properties.Update();
            web.AllowUnsafeUpdates = false;
        }
        private void updateRibbonMenu(List<RibbonLibraryItem> rliList)
        {
            int i = 1;
            StringBuilder ribbonMenu = new StringBuilder();
            foreach (RibbonLibraryItem rli in rliList)
            {
                ribbonMenu.AppendFormat(rli.DocumentsTextString + "|" + rli.RibbonItemsTextString + "|" + rli.GroupsTextString);
                if (i++ != rliList.Count)
                    ribbonMenu.Append(";");
            }
            // Sätt webb property!
            SPWeb web = SPContext.Current.Web;
            web.AllowUnsafeUpdates = true;
            if (web.Properties[ribbonMenuItems] == null)
                web.Properties.Add(ribbonMenuItems, ribbonMenu.ToString());
            else
                web.Properties[ribbonMenuItems] = ribbonMenu.ToString();
            web.Properties.Update();
            web.AllowUnsafeUpdates = false;

        }
        private ArrayList stringArrayToArrayList(string[] alSplit)
        {
            ArrayList al = new ArrayList();
            foreach (string obj in alSplit)
            {
                al.Add(obj);
            }
            return al;

        }
        private ArrayList getSelectedItems(ListBox listBox)
        {
            ArrayList al = new ArrayList();
            foreach (ListItem listItem in listBox.Items)
            {
                if (listItem.Selected)
                {
                    al.Add(listItem.Text);
                }
            }
            return al;
        }
        private void bindGroups()
        {
            using (SPWeb web = SPContext.Current.Web)
            {
                groupListBox.DataSource = web.Groups;
                groupListBox.DataBind();
            }
        }
        private void bindRibbonItems()
        {
            string path = Server.MapPath("ribbonMenus.txt");
            ArrayList al = new ArrayList();
            using (StreamReader sr = new StreamReader(path))
            {
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    al.Add(line);
                }
            }
            ribbonItemsListBox.DataSource = al;
            ribbonItemsListBox.DataBind();
        }
        private void bindDocumentLibraries()
        {
            using (SPWeb web = SPContext.Current.Web)
            {
                librariesListBox.DataSource = web.Lists;
                librariesListBox.DataTextField = "Title";
                librariesListBox.DataValueField = "ID";
                librariesListBox.DataBind();
            }
        }
        private void deleteRibbonItem(int index)
        {
            List<RibbonLibraryItem> rliList = getWebPropertyRibbonMenu();
            rliList.RemoveAt(index);
            updateRibbonMenu(rliList);
            bindRepeater();
        }
        private void editRibbonItem(int index)
        {
            // Få tag i RLI
            List<RibbonLibraryItem> rliList = getWebPropertyRibbonMenu();
            RibbonLibraryItem rli = rliList[index];

            // Set values
            setSelectedValues(rli);

            // Visa Cancel och update
            cancelImg.Visible = true;
            saveImg.Visible = true;
            addImageButton.Visible = false;

            bindRepeater();
        }
        private void setSelectedValues(RibbonLibraryItem rli)
        {
            librariesListBox.ClearSelection();
            ribbonItemsListBox.ClearSelection();
            groupListBox.ClearSelection();

            foreach (string library in rli.Documents)
            {
                if (library.Length > 0 && librariesListBox.Items.FindByText(library) != null)
                {
                    librariesListBox.Items.FindByText(library).Selected = true;
                    
                }
            }

            foreach (string name in rli.RibbonItems)
            {
                if (name.Length > 0 && ribbonItemsListBox.Items.FindByText(name) != null)
                {                    
                    ribbonItemsListBox.Items.FindByText(name).Selected = true;                    
                }
            }

            foreach (string name in rli.Groups)
            {
                if (name.Length > 0 && groupListBox.Items.FindByText(name) != null)
                    groupListBox.Items.FindByText(name).Selected = true;
            }

        }
        private void bindRepeater()
        {
            documentRibbonRepeater.DataSource = getWebPropertyRibbonMenu();
            documentRibbonRepeater.DataBind();
        }
        #endregion
    }
}
